package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //    请求发送验证码
   @PostMapping("/sendMsg")
    public R<String> sendMsging(@RequestBody User user, HttpSession session) {
//        获取手机号
        String phone = user.getPhone();
//        判断
        if (StringUtils.isNotEmpty(phone)) {
            //        随机生成验证码
            String s = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("s={}", s);
//        调用阿里云提供的短信服务发送短信
//            SMSUtils.sendMessage(phone,s);
//        需要将生成的验证码保存在session中
//            session.setAttribute(phone, s);
//            将生成的验证码存在Redis中
            redisTemplate.opsForValue().set(phone,s,5, TimeUnit.MINUTES);
            return R.success("手机验证码发送成功");
        }
        return R.error("验证码发送失败");
    }
//登录验证
    @PostMapping("/login")
    public R<User> userR(@RequestBody Map map, HttpSession session) {
        log.info("map:{}", map);
//        获取前端手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
//        获取session中存取的验证码
//        String s = session.getAttribute(phone).toString();
//        获取Redis中的验证码
        String s = (String) redisTemplate.opsForValue().get(phone);

        if (s != null & code.equals(s)) {
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
//            登录成功后删除验证嘛
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
